/*
 	Script: GearsORM.Events.js
 	        Event support for GearsORM 
 	
 	License:
 	        MIT-style license.
*/

/*
 Class: GearsORM.Events
 	add event support to a class
 	
 Constructor:
 
 */
GearsORM.Events = function()
{
	this.$events = {};
}
GearsORM.Events.prototype = 
{
	/*
	 Function: addListener
	  add a listner on a specific event
	  
	 Parameters:
	 	name - name of the event
	 	fn - function to call when the event is fired
	 */
	addListener:function(name,fn)
	{
		this.$events[name] = this.$events[name] || [];
		this.$events[name].push(fn);
		return this;	
	},
	/*
	 Function: removeListener
	  remove the listner on a specific event
	  
	 Parameters:
	 	name - name of the event
	 	fn - function to call when the event is fired
	 */
	removeListener:function(name,fn)
	{
		if(this.$events[name])
			this.$events[name].remove(fn);
		return this;
	},
	/*
	 Function: fireEvent
	  fires the event
	  
	 Parameters:
	 	name - name of the event
	 	args - arguments to send to the listeners
	 	bind - a object to bind listeners to
	 */
	fireEvent:function(name,args,bind)
	{
		var listeners = this.$events[name];
		if(listeners)
			for(var i=0,ln=listeners.length;i<ln;i++)
				listeners[i].apply(bind || this,args || [])
		return this;
	}
}
/*
 Function: wrapFunction
  wrap a function with a onBefore and onAfter events
  
 Parameters:
 	fn - function to wrap
 	name - name of the function to wrap
 	object - the object who fire the events
 */
GearsORM.Events.wrapFunction=function(fn,name,object)
{
	return function()
	{
		object.fireEvent("onBefore"+name,[this]);
		var ret = fn.apply(this,arguments);
		object.fireEvent("onAfter"+name,[this]);
		return ret;
	};
};